import Axios from 'axios';
require('es6-promise').polyfill();
import Apis from './apis.js';
import Tools from './tools.js';
import CONFIG from './config';
import { reportError } from './handleError';

const Dialog = require('../pages/MyPackage/components/Dialog');
const Toast = require('../pages/MyPackage/components/Toast');
const serializeError = require('serialize-error');

import weui from 'weui.js';

// Axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded'
export default {
    common: CONFIG.ajax_common,
    new_common: CONFIG.new_common,

    getWxCode(cb) {
        // const wx_type = Tools.readCookie('wx_type');
        const wx_type = window.localStorage.getItem('wx_type');
        const params = wx_type === 'garden' ? {
            full_url: window.location.href,
            wx_type: wx_type
        } : {
            full_url: window.location.href,
            wx_type: 'logis'
        };
        this.request('get_auth_url', params, (data) => {
            window.location.href = data.body.auth_url;
        });
    },

    getWxSid(callback) {
        const param = Tools.getParams()
        //url里也没有 code
        if (!param.code) {
            this.getWxCode()
        } else {//url 里有 code
            // const wx_type = Tools.readCookie('wx_type');
            const wx_type = window.localStorage.getItem('wx_type');
            const params = wx_type === 'garden' ? {
                code: param.code,
                wx_type: wx_type
            } : {
                code: param.code,
                wx_type: 'logis'
            };
            this.request('login', params, (data) => {
                const sid = data.body.sid
                const openId = data.body.open_id
                Tools.createCookie('sid', sid, data.body.time, data.body.expires)
                Tools.createCookie('openId', openId, data.body.time, data.body.expires)
                callback(sid)
            })
        }
    },

    request(interface_name, params = {}, handler, redirect) {
        let date = new Date()
        const route = Apis[interface_name]
        params.datastr = Date.parse(date)

        const sid = Tools.readCookie('sid')

        // 兼容处理，get_signature时添加 wx_type
        if (interface_name === 'get_signature' || interface_name === 'recharge_submit') {
            // const wx_type = Tools.readCookie('wx_type');
            const wx_type = window.localStorage.getItem('wx_type');
            params.wx_type = wx_type === 'garden' ? 'garden' : 'logis';
        }

        if (interface_name === 'get_auth_url' || interface_name === 'login') {
            //特殊处理，login 的时候不需要传 sid
            this.get(params, route, handler)()
        } else if (sid) {
            params.sid = sid
            this.get(params, route, handler, redirect)()
        } else {
            this.getWxSid(this.get(params, route, handler))
        }
    },

    get(params, route, handler, redirect) {
        return (sid) => {
            if (sid) {
                params.sid = sid
            }

            const url = route.indexOf('wechat/') > -1 ? `${this.new_common}/${route}` : `${this.common}/${route}`;
            
            Axios.get(url, {
                params: params,
                // headers: headers,
            }).then(response => {
                const { code, msg } = response.data;
                // 20022 后面两种用于绑定手机
                // 40002 用于开箱
                // 20011 验证码太频繁
                // 15407 寄件人姓名与认证姓名不符
                // 15119 快递已取走
                // 40000 开箱'路由不存在'
                // 40001 开箱'客户端不活跃'
                // 40002 开箱'客户端已断开'
                // 40003 开箱'Broker通讯错误'
                if ([0, 20010, 20022, 40002, 20011, 15407, 15119, 40000, 40001, 40002, 40003, 56003].includes(code)) {
                    handler(response.data);
                } else if (code === 2) {
                    Dialog.info({
                        title: '出错了',
                        content: msg || '内部错误',
                        okText: '确认',
                        onOK: () => {
                            if (redirect) {
                                window.location.href = redirect
                            } else {
                                //跳转首页
                                const wx_type = window.localStorage.getItem('wx_type');
                                window.location.href = `./PickUp?wx_type=${wx_type}`;
                            }
                        }
                    })
                } else if (code === 20001) {
                    if (redirect) {
                        window.location.href = redirect
                    } else {
                        window.location.href = './Redirect?source=jlb'
                    }
                } else if (code === 20007) {
                    if (redirect) {
                        window.location.href = redirect
                    } else {
                        window.location.href = './BindPhone'
                    }
                } else if (code === 4) {
                    Dialog.info({
                        title: '出错了',
                        content: '外部错误',
                        okText: '确认',
                        onOK: () => {
                            if (redirect) {
                                window.location.href = redirect
                            } else {
                                //跳转首页
                                const wx_type = window.localStorage.getItem('wx_type');
                                window.location.href = `./PickUp?wx_type=${wx_type}`;
                            }
                        }
                    })
                } else if (code === 6) {
                    //清除sid,刷新页面
                    Toast.loading({
                        content: '正在获取微信授权...'
                    });
                    Tools.eraseCookie('sid');
                    location.reload(true)
                } else if (code === 15220) {
                    Dialog.info({
                        title: '出错了',
                        content: 'VIP账号无效',
                        okText: '确认',
                        onOK: () => {
                        }
                    })
                } else if (code === 15225) {
                    Dialog.info({
                        title: '出错了',
                        content: '您的VIP账号不支持所选快递公司，请更换快递公司',
                        okText: '确认',
                        onOK: () => {
                        }
                    })
                } else if (code === 61152) {
                    //添加代收人 手机号重复
                    Dialog.info({
                        title: '出错了',
                        content: msg,
                        okText: '确认',
                        onOK: () => {
                        }
                    })
                } else if (code === 10005) {
                    //再次开箱，格口被占用
                    Dialog.info({
                        title: '出错了',
                        content: '格口已被投递占用',
                        okText: '确认',
                        onOK: () => {
                        }
                    })
                } else if (code === 15409 || code === 10012) {
                    //'您的订单已投递完成'
                    Dialog.info({
                        title: '',
                        content: msg,
                        okText: '确认',
                        onOK: () => {
                            if (redirect) {
                                window.location.href = redirect
                            } else {
                                //跳转首页
                                const wx_type = window.localStorage.getItem('wx_type');
                                window.location.href = `./PickUp?wx_type=${wx_type}`;
                            }
                        }
                    })
                } else {
                    Dialog.info({
                        title: '出错了',
                        content: msg,
                        okText: '确认',
                        onOK: () => {
                            //跳转首页
                            if (redirect) {
                                window.location.href = redirect
                            } else {
                                //跳转首页
                                const wx_type = window.localStorage.getItem('wx_type');
                                window.location.href = `./PickUp?wx_type=${wx_type}`;
                            }
                        }
                    })
                }
            }).catch(function (error) {
                if (typeof error === 'object' && error.config) {
                    // 判断是由于网络请求出的错误
                    Dialog.confirm({
                        title: '出错了',
                        content: error,
                        okText: '回首页',
                        cancelText: '取消',
                        onOK: () => {
                            if (redirect) {
                                window.location.href = redirect
                            } else {
                                //跳转首页
                                const wx_type = window.localStorage.getItem('wx_type');
                                window.location.href = `./PickUp?wx_type=${wx_type}`;
                            }
                        },
                        onCancel: () => {
                        }
                    })
                } else {
                    const msg = error.message || '异常错误';
                    // warn(msg);
                }
            })
        }
    },

    post(params, route, handler) {
        return (sid) => {
            if (sid) {
                params.sid = sid
            }
            Axios.post(`${this.common}/${route}`, {
                params: params
            }).then(response => {
                const { code } = response.data;

                if (code === 0) {
                    handler(response.data);
                } else {
                    Dialog.info({
                        title: '出错了',
                        content: response.data.msg,
                        okText: '确认',
                        onOK: () => {
                            // 跳转首页
                            const wx_type = window.localStorage.getItem('wx_type');
                            window.location.href = `./PickUp?wx_type=${wx_type}`;
                        }
                    })
                }
            })
        }
    },

    appendBaiduAnalysis(cb) {
        // 百度统计
        // if(CONFIG.ENVIRONMENT === 'DEVELOP') return;
        var BAIDU_TONGJI_ID = CONFIG.baidu_id;
        var hm = document.createElement('script');
        hm.src = 'https://hm.baidu.com/hm.js?' + BAIDU_TONGJI_ID;
        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(hm, s);
        hm.onload = () => {
            if (cb) cb();
        }
    },

    fetchGet(interface_name, params, handle) {
        const route = Apis[interface_name]
        const sid = Tools.readCookie('sid')
        const openId = Tools.readCookie('openId')
        if (sid && openId) {
            params.sid = sid
            interface_name.indexOf('record') >= 0 ? params.open_id = openId : null
        }

        Axios.get(`${this.common}/${route}`, {
            params: params,
            headers: {
                'Content-Type': 'application/json;charset=UTF-8'
            },
        }).then(response => {
            if (response.data.code == 0) {
                handle(response.data.result);
            } else {
                this.errorLog()
            }
        }).catch(error => {
            //  this.errorLog()
            console.log(error)
        })
    },

    operPost(interface_name, params, handle) {
        let date = new Date()
        const route = Apis[interface_name]
        params.datastr = Date.parse(date)
        const sid = Tools.readCookie('sid')
        const openId = Tools.readCookie('openId')
        if (sid && openId) {
            params.sid = sid
            params.openId = openId
        }
        let loading = weui.loading('加载中', {
            className: 'custom-classname'
        });
        Axios.post(`${this.common}/${route}`, params
        ).then(response => {
            loading.hide();
            switch (response.data.code) {
                case 0:
                    handle(response);
                    break;
                default:
                    this.errorLog()
            }
        }).catch(error => {
            loading.hide();
            // this.errorLog()
            console.log(error)
        })
    },

    errorLog() {
        Dialog.info({
            title: '出错了',
            content: '请稍后重试',
            okText: '确认',
            onOK: () => {
                //刷新
                window.location.reload()
            }
        })
    }
}
